#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <cerrno>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <stdio.h>
#include <cstring>

#define NUM 1024
const uint16_t port = 8080;
// udp_server
int main()
{
    // 1.创建套接字
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        std::cerr << "sock create error:" << errno << std::endl;
        return 1;
    }
    // 2.绑定
    struct sockaddr_in local;
    local.sin_family = AF_INET;
    local.sin_port = htons(port);
    local.sin_addr.s_addr = INADDR_ANY;
    if (bind(sock, (sockaddr *)&local, sizeof(local)) < 0)
    {
        std::cerr << "bind error :" << errno << std::endl;
        return 2;
    }
    // 3. 提供服务
    bool quit = false;

    char buffer[NUM];
    while (!quit)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        ssize_t cnt = recvfrom(sock, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&peer, &len);
        
        if (cnt > 0)
        {
            buffer[cnt] = 0;
            FILE *fp = popen(buffer, "r");
            std::string echo;
            char line[1024] = {0};
            while(fgets(line, sizeof(buffer), fp) != NULL)
            {
                echo += line;
            }
            pclose(fp);
            std::cout << "client# " << buffer << std::endl;
            sendto(sock, echo.c_str(), echo.size(), 0, (sockaddr *)&peer, len);
            
        }
    }
    return 0;
}